<template>
    <div class="load">
        <div>
            <!-- 表单 -->
            <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="120px">
                <el-form-item label="请选择时间" prop="yearTime">
                    <el-input v-model="ruleForm.yearTime" placeholder="请选择所教学生入学时间"></el-input>
                </el-form-item>
                <el-form-item label="请选择学校" prop="schoolName">
                    <el-select v-model="ruleForm.schoolName" placeholder="请选择学校信息">
                        <el-option v-for="item in school_name" :key="item.value" :label="item.label"
                            :value="item.label"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="成绩录入时间" prop="time">
                    <el-date-picker v-model="ruleForm.time" type="month" placeholder="选择月份" >
                    </el-date-picker>

                </el-form-item>
            </el-form>
            <!-- 文件上传 -->
            <el-upload class="upload-demo" drag :show-file-list="false" accept=".xlsx,.xls" @change="handleFileUpload">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    拖拽上传 或者 <em>点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">只能上传xlx文件</div>
                </template>
            </el-upload>
        </div>

        <!-- 显示数据 -->
        <!-- <div v-if="excelData.length > 0">
            <h3>处理后的 Excel 数据：</h3>
            <pre>{{ excelData }}</pre>
        </div> -->
    </div>
</template>

<script setup>
import { ref, reactive, toRefs } from "vue";
import * as XLSX from "xlsx";
import { UploadFilled } from "@element-plus/icons-vue";
const { proxy } = getCurrentInstance();
const { school_name } = proxy.useDict('school_name');
import { listIndicator } from "@/api/indicator/indicator";
import dayjs from "dayjs"
// 示例数据：匹配指标名称和 ID
const indicators = ref([])
const hasTriggered = ref(false); // 标志位，防止重复触发上传事件
// 响应式数据

const data = reactive({
    ruleForm: {
        yearTime: "",
        schoolName: "",
        time: ""
    },
    rules: {
        yearTime: [
            { required: true, message: "入学时间不能为空", trigger: "blur" },
        ],
        schoolName: [
            { required: true, message: "学校信息不能为空", trigger: "blur" },
        ],
        time: [
            { required: true, message: "成绩月份不能为空", trigger: "blur" },
        ],
    }
})

const { ruleForm, rules } = toRefs(data);
const excelData = ref([]);
async function getIndicatorList() {

    const data = {
        SchoolID: ruleForm.value.schoolName,
        GradeID: ruleForm.value.yearTime,
    };

    try {
        const res = await listIndicator(data);
        if (res.code === 200) {
            // 清空 indicators 数组，防止数据重复
            indicators.value = [];
            res.data.forEach(item => {
                indicators.value.push({
                    id: item.treeCode,
                    label: item.description,
                });
            });
        }
    } catch (error) {
        console.error('Error fetching data:', error);
    }

}
// 文件上传处理函数
const handleFileUpload = async (file) => {
    // 检查学校信息和入学时间
    if (!ruleForm.value.yearTime || !ruleForm.value.schoolName) {
        proxy.$message.error("请先选择入学时间和学校信息！");
        return;
    }

    // 如果已经触发过，就不再执行
    if (hasTriggered.value) return;

    // 设为已触发，防止重复执行
    hasTriggered.value = true;

    // 获取指标列表
    await getIndicatorList();

    const reader = new FileReader();
    reader.onload = (e) => {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: "binary" });

        // 获取第一个工作表
        const sheet = workbook.Sheets[workbook.SheetNames[0]];
        if (!sheet) {
            console.error("工作表为空！");
            return;
        }

        // 将工作表内容转换为 JSON 格式
        const jsonData = XLSX.utils.sheet_to_json(sheet);
        if (jsonData.length === 0) {
            console.error("读取到的数据为空！");
            return;
        }

        // 数据处理
        excelData.value = jsonData.flatMap((item) => {
            const { 批次号, 班级代码, 扫描序号, 学生学号, ...rest } = item;

            // 用来存储每个学生每个指标的条目
            const indicatorEntries = [];

            // 遍历每个字段，找到加分或减分指标
            Object.entries(rest).forEach(([key, value]) => {
                // 去除字符串前后的符号和空格
                const cleanedKey = key.trim().replace(/^[^\w\u4e00-\u9fa5]+|[^\w\u4e00-\u9fa5]+$/g, '');

                const match = cleanedKey.match(/(.+)(加分|减分)/);
                if (match) {
                    const [, metric, type] = match;
                    const indicator = indicators.value.find((ind) => ind.label === metric);
                    const id = indicator ? indicator.id : null;
                    const name = indicator ? indicator.label : null;

                    // 如果找到了对应的指标，则计算分数并加入列表
                    if (id && name) {
                        const existingEntry = indicatorEntries.find(entry => entry.id === id);

                        // 如果该指标已经存在，则累加分数
                        if (existingEntry) {
                            existingEntry.score += type === "加分" ? (parseInt(value, 10) || 0) : -(parseInt(value, 10) || 0);
                        } else {
                            // 否则创建新的条目
                            indicatorEntries.push({
                                批次号,
                                班级代码,
                                扫描序号,
                                学生学号,
                                id,
                                name,
                                score: type === "加分" ? (parseInt(value, 10) || 0) : -(parseInt(value, 10) || 0),
                            });
                        }
                    }
                }
            });

            // 返回每个学生每个指标的单独对象
            return indicatorEntries;
        }).flat(); // 使用 flatMap 生成一个扁平的数组
        addScoreList();

    };

    // 读取文件内容
    reader.readAsBinaryString(file.raw);
};
import { addScore, updateScore } from "@/api/score/score";
function addScoreList() {
    var flag = 1
    excelData.value.forEach(item => {
        const Adddata = {}
        Adddata.studentID = item.学生学号;
        Adddata.indicatorID = item.id;
        Adddata.score = item.score;
        // 格式化日期为 yyyy-MM-dd 格式
        Adddata.evaluationDate = dayjs(ruleForm.value.time).format("YYYY-MM-DD");
        Adddata.name = item.name
        addScore(Adddata).then(res => {
            if (res.code !== 200) flag = 0
        })

    })
    if (flag) proxy.$modal.msgSuccess("导入成功")
    else proxy.$modal.msgError("导入失败")
    hasTriggered.value = false;
    excelData.value = []
}

</script>

<style scoped lang="less">
.load {
    padding: 20px;
    text-align: center;
}

.el-upload__text {
    margin: 20px 0;
}

pre {
    text-align: left;
    white-space: pre-wrap;
    word-wrap: break-word;
}
</style>